package com.cola.NIO16;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @Grup:com.cola.NIO16
 * @Auther:cola
 * @Data:2021/3/22-2021-03-15:12
 * @version:1.0
 *
 * 比较IO操作的性能比较:
 * 1.内存映射最快
 * 2.NIO读写文件
 * 3.使用缓存的IO流
 * 4.无缓存的IO流
 *
 * 通过文件通道实现文件的复制
 */
public class CopyFileDemo {
    private static void copyFile() throws FileNotFoundException {
        //创建一个输入文件的通道
        FileChannel fcIn=new FileInputStream("FileAndIO_08/src/main/newFile/information/aca.text").getChannel();
        //创建一个输出文件的通道
        FileChannel fcOut=new FileOutputStream("FileAndIO_08/src/main/newFile/aca.text").getChannel();
        ByteBuffer buf=ByteBuffer.allocate(1024);
        try {
            while (fcIn.read(buf)!=-1){
                buf.flip();
                fcOut.write(buf);
                buf.clear();
            }
            fcIn.close();
            fcOut.close();
            System.out.println("copy success.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static void randomAccessFileCopy() throws FileNotFoundException {

            RandomAccessFile in=new RandomAccessFile("FileAndIO_08/src/main/newFile/information/aca.text","r");
            RandomAccessFile out=new RandomAccessFile("FileAndIO_08/src/main/newFile/aca.text","rw");
            FileChannel fcin=in.getChannel();
            FileChannel fcout=out.getChannel();
        long size= 0;//输入流的字节大小
        try {
            size = fcin.size();
            //输入流的缓存区
            MappedByteBuffer inbuf=fcin.map(FileChannel.MapMode.READ_ONLY,0,size);
            //输出流的缓存区
            MappedByteBuffer outbuf=fcout.map(FileChannel.MapMode.READ_WRITE,0,size);
            for (int i=0;i<size;i++){
                outbuf.put(inbuf.get(i));
            }
            //关闭(关闭通道时会写入数据块)
            fcin.close();
            fcout.close();
            in.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


            System.out.println("copy seccess.");

    }

    public static void main(String[] args) {
        try {
            //copyFile();
            randomAccessFileCopy();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
